<script lang="ts" setup>
import { postCollectApi } from '@/services/eat'
import { getMachineDataApi } from '@/services/home'
import { useDeviceStore, useMemberStore, useLocationStore, usePhoneStore } from '@/stores'
import type { spotItem } from '@/types/eat'
import { onLoad, onUnload } from '@dcloudio/uni-app'
import { reactive, ref, watch } from 'vue'
import { MyShowModal, PageSkip, Toast } from '@/utils/tools'

const phoneStore = usePhoneStore()
const deviceStore = useDeviceStore()
const locationStore = useLocationStore()

const myCity = ref('杭州市')
let locationParm = ref<{ longitude: string; latitude: string }>()
onLoad(() => {
  myCity.value = JSON.parse(uni.getStorageSync('location'))?.location?.cityName || '杭州市'
  uni.getLocation({
    type: 'gcj02',
    accuracy: 'best',
    geocode: true,
    success: (success: UniApp.GetLocationSuccess) => {
      // console.log(success)
      locationParm.value = { longitude: success.longitude + '', latitude: success.latitude + '' }
      locationStore.setLocation(locationParm.value)
      getspotListFn()
    },
    fail: (error) => {
      console.log('error', error)
      if (error.errCode === 2) {
        MyShowModal(
          '请在系统设置中打开位置授权后重新进入小程序，以便我们为您提供更好的服务',
          '您未开启地理位置授权',
        )
      } else {
        MyShowModal(
          '请在系统设置中打开位置授权，以便我们为您提供更好的服务',
          '您未开启地理位置授权',
        ).then((res) => {
          if (res.confirm) {
            wx.openSetting()
          }
        })
      }
    },
  })
})

const memberStore = useMemberStore()
let covers = reactive<
  {
    id: number
    latitude: number
    longitude: number
    iconPath: string
    width: number
    height: number
    alpha: number
    callout: {
      content: string
      color: string
      fontSize: number
      bgColor: string
      display: string
      padding: number
      borderRadius: number
    }
  }[]
>([])

/**
 *
 * * onCallouttap 点击标记点对应的气泡时触发
 */
const onCallouttap = (e: any) => {
  console.log(e)
  const deviceInfo = searchList.value!.find((item: any, index) => {
    if (index == e.detail.markerId) return item
  })
  deviceStore.setDeviceInfo(deviceInfo)
  uni.switchTab({ url: '/pages/eat/eat' })
}
let myMap = ref('myMap') // 定义 map 的id
/**
 ** 点击 icon 重新定位
 */
const rePosition = () => {
  const mapCtx = uni.createMapContext(myMap.value) // 点击的时候绑定 map 的id
  const position = ref({
    longitude: Number(locationParm.value?.longitude),
    latitude: Number(locationParm.value?.latitude),
  })
  // console.log(memberStore.location)
  mapCtx.moveToLocation(position.value) // 重新定位
}
// 搜索确定后
const searchList = ref<any[]>([])
const searchValue = ref('') // 搜索的值

/**
 * *  pushListMarkers 添加到地图上的设备信息
 */
const pushListMarkers = () => {
  covers.length = 0
  // console.log('进入触发')
  searchList.value?.forEach((item: any, index) => {
    covers.push({
      id: index,
      latitude: Number(item.latitude),
      longitude: Number(item.longitude),
      iconPath: '',
      width: 32,
      height: 32,
      alpha: 0.9,
      callout: {
        content: item.machineName,
        color: '#000000E5',
        fontSize: 13,
        bgColor: '#fff',
        display: 'ALWAYS',
        padding: 8,
        borderRadius: 4,
      },
    })
  })
  // console.log('成功触发')
}
/**
 * * onClear 清空搜索框
 */
const onClear = () => {
  searchValue.value = '' // 清空搜索框
  getspotListFn()
}

/**
 * * onBack 返回上一页
 */
const onBack = () => {
  PageSkip('/pages/eat/eat', 'switchTab')
}
/**
 ** 点击收藏按钮触发
 *
 */
const onCollect = async (item: spotItem) => {
  if (memberStore.userInfo) {
    const objItem = {
      clientId: memberStore.userInfo.id,
      machineId: item.machineId,
    }
    await postCollectApi(objItem)
    Toast(item.isBookmark ? '取消收藏' : '已收藏')
    getspotListFn()
  } else {
    BjsPopupRef.value.open()
  }
}

const BjsPopupRef = ref()
/**
 *
 * * clickFn 获取选中设备组件传过来的 item
 * * e item 的数据
 */
const myClick = (e: any) => {
  deviceStore.setDeviceInfo(e)
  // console.log(deviceStore.deviceInfo)
  PageSkip('/pages/eat/eat', 'switchTab')
}

/**
 * * 获取设备列表信息
 */
const getspotListFn = async () => {
  // console.log('进入地图界面')
  const res = await getMachineDataApi({
    clientId: memberStore.userInfo?.id || '',
    machineName: searchValue.value,
    longitude: locationStore.location!.longitude,
    latitude: locationStore.location!.latitude,
    pageNum: pageNum.value,
    pageSize: 50,
  })
  searchList.value = res.data
  pushListMarkers()
  // 判断是否在返回的设备list 操作了本地的设备信息
  res.data.find((item: spotItem) => {
    item.machineId === deviceStore.deviceInfo?.machineId
      ? (deviceStore.deviceInfo!.isBookmark = item.isBookmark)
      : ''
  })
}
let pageNum = ref(1)
const isPolling = ref(false)
/**设置轮询 */
// const polling = setInterval(() => {
//   if (isPolling.value) return
//   getspotListFn()
// }, 3000)
// onUnload(() => {
//   clearInterval(polling)
// })

// 公共弹出框
import usePopup from '@/hooks/usePopup'
const { SkipPopupRef, receive, skipPopupData } = usePopup()
</script>

<template>
  <view class="MapBox">
    <!-- 地图 -->
    <map
      :id="myMap"
      :ref="myMap"
      class="map"
      :longitude="Number(locationParm?.longitude)"
      :latitude="Number(locationParm?.latitude)"
      :min-scale="3"
      :max-scale="20"
      :enable-zoom="true"
      :show-location="true"
      :show-position="true"
      :markers="covers"
      @callouttap="onCallouttap"
    >
      <view
        @tap="onBack"
        :style="{ top: phoneStore.phoneInfo?.top + 'px' }"
        class="onBack iconfont icon_base_left"
      ></view>
      <view class="position iconfont icon_position" @tap="rePosition"></view>
    </map>
    <!-- 搜索以及显示设备名称信息 -->
    <view class="spotBox">
      <!-- 搜索框 -->
      <view class="search">
        <view class="searchBox">
          <view class="city">{{ myCity }}&nbsp;&nbsp;|</view>
          <input
            class="_input"
            @confirm=";(isPolling = false), getspotListFn()"
            @focus="isPolling = true"
            @blur="isPolling = false"
            v-model="searchValue"
            placeholder="搜索取餐机"
            type="text"
          />
          <view class="onClear iconfont icon_close1" @tap="onClear"></view>
        </view>
      </view>
      <!-- 设备信息 -->
      <scroll-view enhanced :show-scrollbar="false" style="min-height: 40vh" scroll-y>
        <view class="scroll">
          <!-- <view class="scrollText">附近取餐机</view> -->
          <BjsSpotItem
            @collect="onCollect"
            v-if="searchList.length > 0"
            @myClick="myClick"
            :flag="true"
            :list="searchList"
          />
          <view v-else class="dontSpotBox">
            <image class="dontSpot" src="/static/images/meiyou.png" mode="scaleToFill" />
            <view class="dontSpotText">您的附近暂时还没有设备哦~</view>
          </view>
        </view>
      </scroll-view>
    </view>
    <BjsPopup ref="BjsPopupRef" />
  </view>
  <BjsSkipPopup :img="skipPopupData.img" ref="SkipPopupRef" @receive="receive" />
</template>

<style lang="scss">
//
.MapBox {
  height: 100vh;
  display: flex;
  flex-direction: column;
}
// 地图
.map {
  flex: 1;
  position: relative;
  width: 750rpx;
  .onBack {
    position: absolute;
    margin-left: 50rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 64rpx;
    height: 64rpx;
    color: #000000e5;
    border-radius: 50%;
    background-color: #fff;
  }
  .position {
    position: absolute;
    display: flex;
    justify-content: center;
    align-items: center;
    left: 50rpx;
    bottom: 60rpx;
    width: 52rpx;
    height: 52rpx;
    border-radius: 50%;
    background-color: #fff;
    box-shadow: 0px 8rpx 16rpx rgba(0, 0, 0, 0.2);
  }
}
// 搜索以及显示设备名称信息
.spotBox {
  height: 50vh;
  display: flex;
  flex-direction: column;
  background: #fbfbfb;
}
// 搜索框
.search {
  padding: 36rpx 36rpx 0;
  .searchBox {
    display: flex;
    align-items: center;
    background-color: #f0f0f0;
    border-radius: 40rpx;
    .city {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      padding-left: 32rpx;
      height: 64rpx;
      font-size: 30rpx;
      color: #000000e5;
    }
    ._input {
      padding-left: 16rpx;
      height: 80rpx;
      z-index: 1;
      font-size: 30rpx;
      width: 480rpx;
    }
    .onClear {
      position: absolute;
      right: 52rpx;
      color: #00000026;
      font-size: 40rpx;
      z-index: 999;
      width: 40rpx;
      height: 40rpx;
      line-height: 40rpx;
      text-align: center;
    }
  }
}
// 设备信息
.scroll {
  min-height: 100%;
  display: flex;
  flex-direction: column;
  padding: 24rpx;
  padding-bottom: 80rpx;
  background-color: #fbfbfb;
  .scrollText {
    width: 100%;
    align-content: left;
    margin-bottom: 16rpx;
    font-size: 26rpx;
    color: #00000080;
  }
  .dontSpotBox {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    .dontSpot {
      width: 336rpx;
      height: 220rpx;
    }
    .dontSpotText {
      margin-top: 40rpx;
      font-size: 28rpx;
      color: #808080;
    }
  }
}
</style>
